package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import Model.JDBCModel;
import jdbcutil.JDBCUtil;

public class JDBCDaoA {//PreparedStatement
	
	Connection conn = null;
	PreparedStatement ps = null;
	
	public void insert() throws SQLException {
		String sql = "insert into test_demo1.employee(code,name,gender) values(?,?,?)";
		
		conn = JDBCUtil.getConnection();
		ps = conn.prepareStatement(sql);
		
		conn.setAutoCommit(false);	// 取消自动提交 --开启事务
		for(int i=1;i<=10;i++ ) {
			ps.setString(1, "code"+i);
			ps.setString(2, "李华"+i+"号");
			ps.setString(3, "gend"+2*i);
			ps.addBatch(); // 批量处理提供的操作
		}
		int[] result = ps.executeBatch();
		
		ps.clearBatch();
		conn.commit();// 提交事务
		JDBCUtil.close(conn, ps);
		
		System.out.println(result.length);
	}
	
	public void delete() throws SQLException {
		String sql = "delete from test_demo1.employee where code = ?";
		
		conn = JDBCUtil.getConnection();
		ps = conn.prepareStatement(sql);
		
		conn.setAutoCommit(false);
		for(int i=3;i<=5;i++) {
			ps.setString(1, "code"+i);
			ps.addBatch(); // 批量处理提供的操作
		}
		int[] result = ps.executeBatch();
		
		ps.clearBatch();
		conn.commit();// 提交事务
		JDBCUtil.close(conn, ps);
		
		System.out.println(result.length);
	}
	
	public void update() throws SQLException {
		String sql = "update test_demo1.employee set name=?,gender =? where code=?";
		
		conn = JDBCUtil.getConnection();
		ps = conn.prepareStatement(sql);
		
		conn.setAutoCommit(false);
		for(int i=2,j=1;i<=5;i++,j++) {
			ps.setString(1, "张伟"+j+"号");
			ps.setString(2, "gend"+3*j);
			ps.setString(3, "code"+i);
			ps.addBatch(); // 批量处理提供的操作
		}
		int[] result = ps.executeBatch();
		
		ps.clearBatch();
		conn.commit();// 提交事务
		JDBCUtil.close(conn, ps);
		
		System.out.println(result.length);
	}
	public static void main(String[] args) throws SQLException {
		JDBCDaoA dao =new JDBCDaoA();
//		dao.delete();
	}
}
